<?php
namespace app\dao;
/**
 * @desc 类目数据操作
 */
use app\dao\BaseDAO;
use yii\db\Query;
use app\enum\EnumOther;
use yii\base\Object;

class CategoryDAO extends BaseDAO
{
	/**
	 * @desc 构造函数
	 * @author liaojianwen
	 * @date 2016-12-01
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_table = 'category';
		$this->_pKey ='category_id';
		$this->_name = 'category_name';
	}
	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%category}}';
	}
	
	/**
	 * @desc 树状获取产品分类信息
	 * @author zhengyu
	 * @date 2015-12-14
	 * @param int $pcid 分类父id
	 * @param int $status 分类状态
	 * @param int $selectId 选中的id
	 * @param int $isDel 是否删除
	 * @return array
	 */
	public function getCatTreeByPcid($pcid, $selectId = 0, $isDel = 0){
		$result = array();
	
		$query = new Query();
		$queryBuilder = $query->select('category_id, category_name, parent_id')
		->from($this->_table)
		->where(['parent_id'=>$pcid]);
		
	
		if ($isDel !== false){
			$queryBuilder->andWhere(['delete_flag'=>$isDel]);
		}
	
		$catInfo = $queryBuilder->all();
		if ($catInfo){
			foreach ($catInfo as &$catItem){
				$catItem['id'] = $catItem['category_id'];
				$catItem['name'] = $catItem['category_name'];
				$catTmp = array(
						'value'=>$catItem,
						'list'=>$this->getCatTreeByPcid($catItem[$this->_pKey], $selectId),
				);
				if ($catItem[$this->_pKey] == $selectId){
					$catTmp['selected'] = TRUE;
				}
	
				$result[] = $catTmp;
			}
		}
	
		return $result;
	}
	
	/**
	 * @desc 获取类目表
	 * @author liaojianwen
	 * @date 2016-12-2
	 */
	public function getCategoryList()
	{
		$result = array();
		
		$query = new Query();
		$queryBuilder = $query->select('category_id id, category_name name, parent_id pId')
		->from($this->_table)
		->where(['delete_flag' => EnumOther::NO_DELETE]);
		
		$catInfo = $queryBuilder->all();
		return $catInfo;
	}
	
	/**
	 * @desc 根据id 获取cateinfo
	 * @author liaojianwen
	 * @date 2016-12-02
	 */
	public function getCateInfo($id)
	{
		$query = new Query();
		$selections = "a.category_id,a.category_name,a.parent_id,a.remark,b.category_name parent_name";
		
		$conditions ="a.delete_flag = :flag and a.category_id = :id";
		$params =[
			':flag'=>EnumOther::NO_DELETE,
			':id'=>$id,
		];
		$result = $query->select($selections)
				  ->from("$this->_table a")
				  ->leftJoin("$this->_table b","a.parent_id = b.category_id")
				  ->where($conditions,$params)
				  ->one();
		return $result;
	}
}